package source

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/url"
)

const (
	appid   = "20180518000161739"
	scret   = "sEPGZ9ifl2wUyh7JwJAn"
	baseUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate"
)

type transResult struct {
	Src string
	Dst string
}

type respose struct {
	From         string
	To           string
	Trans_result []transResult
}

// 百度源翻译
func TranslateBaidu(q, fromType string) []string {
	var wordMeans []string
	h := md5.New()
	salt := GetRandomSalt()
	h.Write([]byte((appid + q + salt + scret)))

	//根据中英文判断返回值
	var toResult string
	if fromType != "zh" {
		toResult = "zh"
	} else {
		toResult = "en"
	}

	sign := hex.EncodeToString(h.Sum(nil))
	queryWord := url.QueryEscape(q)
	url := baseUrl + "?q=" + queryWord + "&from=auto&to=" + toResult + "&appid=" + appid + "&salt=" + salt + "&sign=" + sign
	// fmt.Println(url)
	body, err := GetJson(url)
	if err != nil {
		fmt.Println("返回结果出错", err)
	}

	var r respose
	if err2 := json.Unmarshal(body, &r); err2 != nil {
		fmt.Println("返回结果出错", err2)
	}

	results := r.Trans_result //获取翻译结果

	for i := 0; i < len(results); i++ {
		wordMeans = append(wordMeans, results[i].Dst)
	}

	return wordMeans
}
